// eslint-disable-next-line complexity
const polyfit = (inputArray) => {
  const { maxValue, minValue } = this.tempParams
  const vals = [Math.abs(maxValue), Math.abs(minValue)]
  const maxVal = Math.max(...vals)
  const rateVal = maxVal > 1000 ? maxVal / 100 : 1
  const userInput = inputArray.map(item => {
    return {
      ...item,
      x: item.x / rateVal
    }
  })
  let returnResult = [];
  this.inputMatrix = [];
  let n = userInput.length;
  for (let i = 0; i < n; i++) {
    let tempArr = [];
    for (let j = 0; j < n; j++) {
      tempArr.push(Math.pow(userInput[i].x, n - j - 1));
    }
    tempArr.push(userInput[i].y);
    this.inputMatrix.push(tempArr);
  }
  for (let i = 0; i < n; i++) {
    let base = this.inputMatrix[i][i];
    for (let j = 0; j < n + 1; j++) {
      if (base === 0) {
        // 存在相同x不同y的点，无法使用多项式进行拟合
        return false;
      }
      this.inputMatrix[i][j] = this.inputMatrix[i][j] / base;
    }
    for (let j = 0; j < n; j++) {
      if (i !== j) {
        let baseInner = this.inputMatrix[j][i];
        for (let k = 0; k < n + 1; k++) {
          this.inputMatrix[j][k] = this.inputMatrix[j][k] - baseInner * this.inputMatrix[i][k];
        }
      }
    }
  }
  for (let i = 0; i < n; i++) {
    if (this.inputMatrix[i][n] > 0 && returnResult.length) {
      returnResult.push('+');
    }

    if (this.inputMatrix[i][n] !== 0) {
      let tmp_x = '';
      for (let j = 0; j < n - 1 - i; j++) {
        tmp_x = tmp_x + '*x';
      }
      returnResult.push((Math.round(this.inputMatrix[i][n] * 10**9) / 10**9 + tmp_x));
    }
  }
  const res = returnResult.join('')
  return rateVal === 1 ? res : res.replace(/x/g, `(x/${rateVal})`);
}

export default polyfit